package com.keyinong.caizhengting.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.ImageUtils;
import com.keyinong.caizhengting.tools.MyShowDialog;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.tools.SystemBarTintManager;
import com.keyinong.caizhengting.activity.PaysuccessActivity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * 付款二维码
 */

public class ErweimaFragment extends Fragment {

    HttpTools httptools = null;
    /**
     * 二维码
     */
    ImageView iv_erweima;
    /**
     * 条码
     */
    ImageView iv_tiaoma;
    /**
     * 编号
     */
    TextView tv_no;
    String balance;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        public void run() {
            try {
                this.update();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            handler.postDelayed(this, 3000);// 间隔1秒刷新一次
        }

        void update() throws IOException {
//			onrefresh.onPullDownToRefresh(list_order);
            getConsume();
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getActivity().getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        return inflater.inflate(R.layout.fragment_erweima, null);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        SystemBarTintManager tintManager = new SystemBarTintManager(
                getActivity());
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintColor(getResources().getColor(
                R.color.white_1));
        super.onActivityCreated(savedInstanceState);
        setWindowBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL);
//		initRes();


    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        getErweima();

    }

    private void initRes() {
        iv_tiaoma = (ImageView) getView().findViewById(R.id.iv_tiaoma);
        iv_erweima = (ImageView) getView().findViewById(R.id.iv_erweima);
        tv_no = (TextView) getView().findViewById(R.id.tv_no);
//		getErweima();

    }

    /**
     * 获取二维码
     */
    private void getErweima() {
        if (NetWorkUtil.isNetwork(getActivity()) == false) {
            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
//		String id = getIntent().getStringExtra("id");
        if (httptools == null) {
            httptools = new HttpTools(getActivity());
        }
        httptools.getErweima(token, new JsonErweima());
    }

    /**
     * 检测付款是否成功
     */
    private void getConsume() {
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
//		String id = getIntent().getStringExtra("id");
        if (httptools == null) {
            httptools = new HttpTools(getActivity());
        }
        httptools.getConsume(token, balance, new JsonGetconsume());
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        handler.removeCallbacks(runnable);
        setWindowBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE);
//		Log.e("zq", "停止----------------");
    }

    /**
     * 设置当前窗口亮度
     *
     * @param brightness
     */
    private void setWindowBrightness(float brightness) {
        Window window = getActivity().getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = brightness;
        window.setAttributes(lp);
    }

    public class JsonErweima extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(getActivity(), "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
            initRes();
            try {
                Log.i("zq", response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    JSONObject object = response.getJSONObject("data");
                    String barcode = object.getString("barcode");
                    String no = object.getString("no");
                    balance = object.getString("balance");
                    String pic = object.getString("pic");
                    handler.postDelayed(runnable, 1000);
//					Log.i("zq", "pic---"+pic);
                    tv_no.setText(no);
                    ImageUtils.displayImage(getActivity(), barcode, iv_tiaoma, R.drawable.wupian1);
                    ImageUtils.displayImage(getActivity(), pic, iv_erweima, R.drawable.wupian1);
                } else {
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public class JsonGetconsume extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            try {
//				Log.i("zq", "扫码-------"+response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    String data = response.getString("data");
                    if (!"0".equals(data)) {
//						Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
                        handler.removeCallbacks(runnable);
                        Intent intent = new Intent();
                        intent.putExtra("xiaofei", data);
                        intent.setClass(getActivity(), PaysuccessActivity.class);
                        startActivity(intent);
                        Log.e("zq", "data--------------" + data);
                    } else {
//						Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
//						Log.e("zq", "data--------------"+data);
                    }
                } else {
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


}
